//
//  L9CorrectionViewController.m
//  INMOTION
//
//  Created by cjg on 2020/4/3.
//  Copyright © 2020 Inmotion. All rights reserved.
//

#import "L9CorrectionViewController.h"
#import "IMTCANManager.h"
#import "CalibrationAlartView.h"
#import "IMTWebViewController.h"
#import "IMFunction.h"
#import "NSObject+HUD.h"
#import "KSLanguageManager.h"

@interface L9CorrectionViewController ()
@property (nonatomic , strong) NSArray *titleS;

@property (nonatomic , strong) NSTimer *timer;
@property (nonatomic , strong) CalibrationAlartView *AlartView;

// 增加刹车把手校正超时终端处理 --- 临时解决车辆bug
@property (nonatomic , assign) BOOL isCorrectionning;
@end

@implementation L9CorrectionViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.AlartView dismiss];
}

- (void)dealloc {
    [self.AlartView dismiss];
}

- (void)backAction {
    [self dismissHUD];
    [self.timer invalidate];
    self.timer = nil;
    [[IMTCANManager sharedInstance] clearMessages];
    if (self.isCorrectionning) {
        uint16_t param = 0x0101;
        NSData *paramData = [NSData dataWithBytes:&param length:2];
        [self.l9CarModel sendMessageWithChannel:1 property:6 dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
        }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = IMTNewCarLocalizedString(@"car_feature_vehicle_calibration");
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"nav_back_white"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = left;

    self.isCorrectionning = NO;
    
    self.tableView.scrollEnabled = NO;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.titleS = @[IMTNewCarLocalizedString(@"car_settings_acc_calibration"),IMTNewCarLocalizedString(@"car_settings_break_calibration"),IMTNewCarLocalizedString(@"car_feature_gyro_calibration")];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (IMTCarSeriesL5(self.l9CarModel.LX_CarType)) {
        return 2;
    }
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"cell"];
    }

    cell.textLabel.text = self.titleS[indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self checkHandleWithType:indexPath.row];
}

// 车辆把手校准 -- 油门、刹车、转向灯
- (void)checkHandleWithType:(uint8_t)type {
    NSString *message = nil;
    if (type == 0) {
        message = IMTNewCarLocalizedString(@"prompt_l9_acc_handle_calibration_tips");
    }else if (type == 1) {
        message = IMTNewCarLocalizedString(@"prompt_l9_break_handle_calibration_tips");
    }else{
        message = IMTNewCarLocalizedString(@"prompt_l9_auto_turn_signal_calibration_tips");
    }
    self.AlartView = [CalibrationAlartView showAlartViewWithTitle:@"" message:message golook:^{
        NSString *typeStr = @"";
        if (type == 0) {
            typeStr = @"calibrate_acc_handle";
        }else if (type == 1){
            typeStr = @"calibrate_break_handle";
        }else if (type == 2){
            typeStr = @"calibrate_gyro";
        }
        NSString *language = [[KSLanguageManager sharedInstance] currentLanguage];
        NSString *languageShortString = kIMTEnglishPrefix;
        if ([language hasPrefix:kIMTSimplifiedChinesePrefix]) {
            languageShortString = @"cn";
        } else if ([language hasPrefix:@"zh-HK"] || [language hasPrefix:kIMTTraditionnalChinesePrefix]) {
            languageShortString = @"hk";
        } else if ([language isEqualToString:kIMTKoreanPrefix]) {
            languageShortString = kIMTKoreanPrefix;
        } else if ([language isEqualToString:kIMTRussianPrefix]) {
            languageShortString = kIMTRussianPrefix;
        }

        IMTWebViewController *web = [[IMTWebViewController alloc] init];
        web.url = [NSString stringWithFormat:@"http://app.imscv.com/api/%@/carOperationGuide?carType=190&type=%@",languageShortString,typeStr];
        [self.navigationController pushViewController:web animated:YES];

    } commit:^{
        NSLog(@"================== 点击确定");
        [self checkWithType:type];
    }];
}

// 校正
- (void)checkWithType:(uint8_t)type {
    [self showProgressHUDWithText:IMTNewCarLocalizedString(@"prompt_calibrating")];
    if (type == 1) {
        self.isCorrectionning = YES;
    }
    // 开启把手矫正
    [self.l9CarModel writeDataWithCmdType:(L9_CarModelCmdTypeCalibrationHandle) uint8Param:type successBlock:^{
        // 超时处理: 使用主线程Runloop来驱动timer
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.timer.isValid) {
                [self.timer invalidate];
                self.timer = nil;
            }
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerFired:) userInfo:@(type) repeats:YES];
        });
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"=======================😄😄😄");
            if (self.timer.isValid) {
                NSLog(@"=======================😄😄😄😄");
                [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(0,-1)",IMTNewCarLocalizedString(@"prompt_calibrate_failed")]];
                [self.timer invalidate];
                self.timer = nil;
                [[IMTCANManager sharedInstance] clearMessages];
                // 刹车把手发送停止方法
                if (type == 1) {
                    uint16_t param = 0x0101;
                    NSData *paramData = [NSData dataWithBytes:&param length:2];
                    [self.l9CarModel sendMessageWithChannel:1 property:6 dataParam:paramData isRead:NO isRepeat:YES repeatcount:0 compleBlock:^(NSError *error, NSData *responseData) {
                    }];
                    self.isCorrectionning = NO;
                }
                
            }
        });
    } failBlock:^(NSError *error) {
        if (error.code == 5) {
            if (type == 0 || type == 1) {
                [self showErrorHUDWithText:IMTNewCarLocalizedString(@"prompt_try_after_car_static")];
            }else {
                [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"prompt_calibrate_failed"),(long)error.code]];
            }
        }else {
            [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(%ld)",IMTNewCarLocalizedString(@"prompt_calibrate_failed"),(long)error.code]];
        }
    }];
}

// 定时获取校准状态
- (void)timerFired:(NSTimer *)timer {
    uint8_t type = (uint8_t)[timer.userInfo intValue];
    [self.l9CarModel getDataWithCmdType:(L9_CarModelCmdTypeHandleCalibrationResult) dataParam:type isRepeat:NO compleBlock:^(NSError *error, NSData *responseData) {
        if (responseData) {
            uint8_t result;
            [responseData getBytes:&result range:NSMakeRange(0, responseData.length)];
            uint8_t value = 0;
            if ([IMFunction isTheVersion:self.l9CarModel.btVersion newerThanAnotherVersion:@"1.3.0"]) {
                value = 1;
            }
            if (result == value+2) {
                [self showSuccessHUDWithText:IMTNewCarLocalizedString(@"prompt_calibrate_success")];
                if (self.timer.isValid) {
                    [self.timer invalidate];
                    self.timer = nil;
                }
                if (type == 1) {
                    self.isCorrectionning = NO;
                }
                [[IMTCANManager sharedInstance] clearMessages];
            }else if (result == value +3 || result == value +4 || result == value +5){
                NSLog(@"=======================😄😄");
                if (self.timer.isValid) {
                    [self.timer invalidate];
                    self.timer = nil;
                }
                if (type == 1) {
                    self.isCorrectionning = NO;
                }
                [[IMTCANManager sharedInstance] clearMessages];
                [self showErrorHUDWithText:[NSString stringWithFormat:@"%@(0,%d)",IMTNewCarLocalizedString(@"prompt_calibrate_failed"),result]];
            }
        }
    }];
}

// 校准结果提示语
- (NSString *)returnResultStringWithCode:(uint8_t)code {
    NSString *resultStr = @"";
    switch (code) {
        case 0:
            resultStr = IMTLocalizedStringFromTable(@"Not calibrated", @"Car", @"");
            break;
        case 1:
            resultStr = IMTLocalizedStringFromTable(@"prompt_calibrating", @"Car", @"");
            break;
        case 2:
            resultStr = IMTLocalizedStringFromTable(@"Calibration Success", @"Car", @"");
            break;
        case 3:
            resultStr = IMTLocalizedStringFromTable(@"prompt_calibrate_failed", @"Car", @"");
            break;
        case 4:
            resultStr = IMTLocalizedStringFromTable(@"Calibration Timeout", @"Car", @"");
            break;
        default:
            break;
    }
    return resultStr;
}

-(double)currentdateInterval {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return [timeSp doubleValue];
}

@end
